var question = [];
var answer = [];
var user_input = [];
var sec = localStorage.getItem("countdown");


var start_time;
var end_time;
var timer;

function startcountdown() {
    timer = setInterval(function () {
        let remain_time = Math.ceil(Math.max(0, end_time - Date.now()) / 1000);
        num.innerHTML = remain_time;
        if (remain_time <= 0) {
            clearInterval(timer);
            nextQuestion();
        }
    }, 10);
}


function updateDisplay() {
    ajaxRequest("../php/recordStartTime.php", 'get', null, function () {
        let quiz_index = localStorage.getItem('index');
        let str = question[quiz_index];
        document.getElementById("QuestionDisplay").innerHTML = str;
        start_time = Date.now();
        end_time = Date.now() + sec * 1000;
        startcountdown();
    }, function () {
        console.error("record start time error")
    });

}

function nextQuestion() {
    clearInterval(timer);
    let record_user_input_url = "../php/recordUserAns.php?input=" + document.getElementById("user_answer").value + "&end=0";
    ajaxRequest(record_user_input_url, 'get', null, function () {
        document.getElementById("user_answer").value = '';
        let quiz_index = parseInt(localStorage.getItem('index')) + 1;
        question = JSON.parse(localStorage.getItem("json_quiz"))['question'];
        if (quiz_index >= question.length) {
            location.replace('../html/grade.html');
        } else {
            localStorage.setItem('index', quiz_index);
            updateDisplay();
        }
    }, function () {
        console.log("record ans error")
    });
}

window.onload = function () {
    function isLogin() {
        if (localStorage.hasOwnProperty("UserName")) {
            document.getElementById("login").style.display = 'none';
            document.getElementById("login-out").style.display = 'block';
            document.getElementById("profile").style.display = 'block';
            document.querySelector("#profile a").innerHTML = 'User: ' + localStorage.getItem('UserName');
        }
        else {
            document.getElementById("login-out").style.display = 'none';
            document.getElementById("login").style.display = 'block';
            document.getElementById("profile").style.display = 'none';
        }
    }
    isLogin();

    function judge() {
        if (sec == 300000000) {
            document.getElementById('countdown').style.display = 'none';
        }
    }
    question = JSON.parse(localStorage.getItem("json_quiz"))['question'];

    judge();
    updateDisplay();
}
